package com.hui.qiniucloud.service.impl;

import com.hui.qiniucloud.constants.JwtClaimsConstant;
import com.hui.qiniucloud.entity.User;
import com.hui.qiniucloud.dto.*;
import com.hui.qiniucloud.mapper.UserMapper;
import com.hui.qiniucloud.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hui.qiniucloud.utils.JwtProperties;
import com.hui.qiniucloud.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author huihui
 * @since 2025-09-28
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private  JwtProperties jwtProperties;
    // 临时简化处理，实际项目应该注入PasswordEncoder
    private String encodePassword(String password) {
        // 这里应该使用BCrypt等加密方式
        return password; // 临时不加密，实际使用时需要配置PasswordEncoder
    }

    private boolean matchesPassword(String rawPassword, String encodedPassword) {
        // 这里应该使用PasswordEncoder.matches
        return rawPassword.equals(encodedPassword); // 临时简化
    }

    @Override
    public UserResponse register(UserRegisterRequest request) {
        // 验证密码确认
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            throw new RuntimeException("两次输入的密码不一致");
        }

        // 检查用户名是否已存在
        if (isUsernameExists(request.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(encodePassword(request.getPassword()));
        user.setNickname(request.getUsername()); // 默认昵称为用户名
        user.setStatus(1); // 默认启用

        boolean saved = save(user);
        if (!saved) {
            throw new RuntimeException("用户注册失败");
        }

        log.info("用户注册成功: {}", request.getUsername());
        return convertToUserResponse(user);
    }

    @Override
    public UserLoginResponse login(UserLoginRequest request, String clientIp) {
        String username = request.getUsername();

        // 根据用户名查找用户
        User user = userMapper.selectActiveByUsername(username);

        if (user == null) {
            throw new RuntimeException("用户不存在或已被禁用");
        }

        // 验证密码
        if (!matchesPassword(request.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 检查用户状态
        if (user.getStatus() == 0) {
            throw new RuntimeException("用户已被禁用");
        }

        // 更新最后登录信息
        userMapper.updateLastLoginInfo(user.getId(), LocalDateTime.now(), clientIp);

        // 生成token (这里简化处理，实际项目中应该使用JWT)
//        String token = generateToken(user);
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);


        UserResponse userResponse = convertToUserResponse(user);

        log.info("用户登录成功: {}", user.getUsername());
        return new UserLoginResponse(token, userResponse);
    }

    @Override
    public UserResponse updateUserInfo(Long userId, UserUpdateRequest request) {
        User user = getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查邮箱是否被其他用户使用
        if (StringUtils.hasText(request.getEmail()) && !request.getEmail().equals(user.getEmail())) {
            User existingUser = userMapper.selectActiveByEmail(request.getEmail());
            if (existingUser != null && !existingUser.getId().equals(userId)) {
                throw new RuntimeException("邮箱已被其他用户使用");
            }
        }

        // 检查手机号是否被其他用户使用
        if (StringUtils.hasText(request.getPhone()) && !request.getPhone().equals(user.getPhone())) {
            User existingUser = userMapper.selectActiveByPhone(request.getPhone());
            if (existingUser != null && !existingUser.getId().equals(userId)) {
                throw new RuntimeException("手机号已被其他用户使用");
            }
        }

        // 更新用户信息
        if (StringUtils.hasText(request.getNickname())) {
            user.setNickname(request.getNickname());
        }
        if (StringUtils.hasText(request.getAvatar())) {
            user.setAvatar(request.getAvatar());
        }
        if (request.getSignature() != null) { // 允许设置为空字符串
            user.setSignature(request.getSignature());
        }
        if (StringUtils.hasText(request.getEmail())) {
            user.setEmail(request.getEmail());
        }
        if (StringUtils.hasText(request.getPhone())) {
            user.setPhone(request.getPhone());
        }

        boolean updated = updateById(user);
        if (!updated) {
            throw new RuntimeException("用户信息更新失败");
        }

        log.info("用户信息更新成功: {}", user.getUsername());
        return convertToUserResponse(user);
    }

    @Override
    public void updatePassword(Long userId, UserPasswordUpdateRequest request) {
        // 验证新密码确认
        if (!request.getNewPassword().equals(request.getConfirmPassword())) {
            throw new RuntimeException("两次输入的新密码不一致");
        }

        User user = getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证当前密码
        if (!matchesPassword(request.getOldPassword(), user.getPassword())) {
            throw new RuntimeException("当前密码错误");
        }

        // 更新密码
        user.setPassword(encodePassword(request.getNewPassword()));
        boolean updated = updateById(user);
        if (!updated) {
            throw new RuntimeException("密码更新失败");
        }

        log.info("用户密码更新成功: {}", user.getUsername());
    }

    @Override
    public UserResponse getUserInfo(Long userId) {
        User user = getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return convertToUserResponse(user);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectActiveByUsername(username);
    }

    @Override
    public boolean isUsernameExists(String username) {
        return userMapper.selectByUsernameIncludeDeleted(username) != null;
    }

    @Override
    public boolean isEmailExists(String email) {
        return userMapper.selectActiveByEmail(email) != null;
    }

    @Override
    public boolean isPhoneExists(String phone) {
        return userMapper.selectActiveByPhone(phone) != null;
    }

    @Override
    public List<UserResponse> searchUsers(String keyword) {
        List<User> users;
        if (StringUtils.hasText(keyword)) {
            users = userMapper.searchByKeyword(keyword);
        } else {
            users = userMapper.selectAllActive();
        }
        return users.stream()
                .map(this::convertToUserResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<UserResponse> getAllUsers() {
        List<User> users = userMapper.selectAllActive();
        return users.stream()
                .map(this::convertToUserResponse)
                .collect(Collectors.toList());
    }

    @Override
    public void updateUserStatus(Long userId, Integer status) {
        User user = getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        user.setStatus(status);
        boolean updated = updateById(user);
        if (!updated) {
            throw new RuntimeException("用户状态更新失败");
        }

        log.info("用户状态更新成功: {} -> {}", user.getUsername(), status == 1 ? "启用" : "禁用");
    }

    /**
     * 转换为用户响应DTO
     */
    private UserResponse convertToUserResponse(User user) {
        UserResponse response = new UserResponse();
        BeanUtils.copyProperties(user, response);
        return response;
    }

    /**
     * 生成token (简化实现)
     */
    private String generateToken(User user) {
        // 这里应该使用JWT等安全的token生成方式
        // 为了简化，这里只是简单的拼接
        return "token_" + user.getId() + "_" + System.currentTimeMillis();
    }
}
